//
//  StadiumNavViewController.m
//  GolfFriend
//
//  Created by Vescky on 14-3-2.
//  Copyright (c) 2014年 vescky.org. All rights reserved.
//

#import "StadiumNavViewController.h"
#import "BMapKit.h"
#import "SVProgressHUD.h"
#import "AppDelegate.h"
#import "CommonUtility.h"
#import "AppsBBubbleAnnotationView.h"
#import "AnimationUtility.h"
#import "RouteAnnotation2.h"

//@interface RouteAnnotation : BMKPointAnnotation
//{
//	int _type; ///<0:起点 1：终点 2：公交 3：地铁 4:驾乘 5:途经点
//	int _degree;
//}
//
//@property (nonatomic) int type;
//@property (nonatomic) int degree;
//@end
//
//@implementation RouteAnnotation
//
//@synthesize type = _type;
//@synthesize degree = _degree;
//@end
//
//@interface UIImage(InternalMethod)
//
//- (UIImage*)imageRotatedByDegrees:(CGFloat)degrees;
//
//@end

@implementation UIImage(InternalMethod)

- (UIImage*)imageRotatedByDegrees:(CGFloat)degrees
{
    
    CGFloat width = CGImageGetWidth(self.CGImage);
    CGFloat height = CGImageGetHeight(self.CGImage);
    
	CGSize rotatedSize;
    
    rotatedSize.width = width;
    rotatedSize.height = height;
    
	UIGraphicsBeginImageContext(rotatedSize);
	CGContextRef bitmap = UIGraphicsGetCurrentContext();
	CGContextTranslateCTM(bitmap, rotatedSize.width/2, rotatedSize.height/2);
	CGContextRotateCTM(bitmap, degrees * M_PI / 180);
	CGContextRotateCTM(bitmap, M_PI);
	CGContextScaleCTM(bitmap, -1.0, 1.0);
	CGContextDrawImage(bitmap, CGRectMake(-rotatedSize.width/2, -rotatedSize.height/2, rotatedSize.width, rotatedSize.height), self.CGImage);
	UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
	UIGraphicsEndImageContext();
	return newImage;
}

@end


@interface StadiumNavViewController ()<BMKMapViewDelegate,BMKSearchDelegate> {
    BMKMapView *navView;
    BMKSearch *bmkSearch;
    bool hasLocation;
    
    UIView *rightActivityView;
    UIActivityIndicatorView *rightActivityLoadingView;
    UILabel *loadingLabel;
    
    RouteAnnotation2 *endAnnotation;
}

@end

@implementation StadiumNavViewController

@synthesize stadiumInfo;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setTitle:@"地图导航"];
    [super customBackButton];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self initView];
    [self initData];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self cleanMapView];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    
}

- (void)initView {
    rightActivityView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 80, 30)];
    [rightActivityView setBackgroundColor:[UIColor clearColor]];
    rightActivityLoadingView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    [rightActivityView setClipsToBounds:YES];
    [rightActivityLoadingView setFrame:CGRectMake(0, 5, 20, 20)];
    [rightActivityView addSubview:rightActivityLoadingView];
    [rightActivityLoadingView setHidesWhenStopped:YES];
    [rightActivityLoadingView startAnimating];
    loadingLabel = [[UILabel alloc] initWithFrame:CGRectMake(25, 0, 60, 30)];
    [loadingLabel setBackgroundColor:[UIColor clearColor]];
    [loadingLabel setTextColor:[UIColor whiteColor]];
    [loadingLabel setFont:[UIFont systemFontOfSize:14]];
    [loadingLabel setText:@"导航中..."];
    [rightActivityView addSubview:loadingLabel];
    [rightActivityView setAlpha:0.0f];
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightActivityView];
    self.navigationItem.rightBarButtonItem = rightItem;
}

- (void)initData {
    stepper.value = 50;
    stepper.tag = stepper.value;
    
    [self initMapView];
    
}

- (void)initMapView {
    //初始化bmkmapview
    if (iPhone5) {
        navView = [[BMKMapView alloc] initWithFrame:CGRectMake(0, 0, 320, 568 - 64)];
    }
    else {
        navView = [[BMKMapView alloc] initWithFrame:CGRectMake(0, 0, 320, 480 - 64)];
    }
    
    navView.showsUserLocation = NO;
    navView.delegate = self;
    navView.scrollEnabled = YES;
    
    [self.view addSubview:navView];
    [self.view bringSubviewToFront:stepper];
    
    [navView setZoomLevel:13];
    
    return;
    
    bmkSearch = [[BMKSearch alloc]init];
    bmkSearch.delegate = self;
    
    BMKPlanNode* start = [[BMKPlanNode alloc] init];
    start.pt = [APP_DELEGATE userCurrentLocation].coordinate;
    start.name = [stadiumInfo objectForKey:@"name"];
    
    CLLocation *stadiumLocation = getGfLocation([stadiumInfo objectForKey:@"position"]);
    BMKPlanNode* end = [[BMKPlanNode alloc] init];
    end.pt = stadiumLocation.coordinate;
    end.name = [stadiumInfo objectForKey:@"name"];
//    BOOL flag = [bmkSearch drivingSearch:@"" startNode:start endCity:@"" endNode:end];
//    NSLog(@"----------nav result:%d",flag);
}

- (void)cleanMapView {
    NSArray* array = [NSArray arrayWithArray:navView.annotations];
    if (array) {
        [navView removeAnnotations:array];
    }
    
    NSArray* array1 = [NSArray arrayWithArray:navView.overlays];
    if (array) {
        [navView removeOverlays:array1];
    }
    
    navView.showsUserLocation = NO;
    navView.userTrackingMode = BMKUserTrackingModeNone;
    navView.delegate = nil;
    bmkSearch.delegate = nil;
}

//设置地图当前显示的区域
- (void)setRegion:(NSMutableArray * )arr
{
    if ([arr count]!=0) {
        // determine the extents of the trip points that were passed in, and zoom in to that area.
        CLLocationDegrees maxLat = -90;
        CLLocationDegrees maxLon = -180;
        CLLocationDegrees minLat = 90;
        CLLocationDegrees minLon = 180;
        
        for(int i = 0; i < [arr count]; i++)
        {
            CLLocation* currentLocation = [arr objectAtIndex:i];
            if(currentLocation.coordinate.latitude > maxLat)
                maxLat = currentLocation.coordinate.latitude;
            if(currentLocation.coordinate.latitude < minLat)
                minLat = currentLocation.coordinate.latitude;
            if(currentLocation.coordinate.longitude > maxLon)
                maxLon = currentLocation.coordinate.longitude;
            if(currentLocation.coordinate.longitude < minLon)
                minLon = currentLocation.coordinate.longitude;
        }
        
        BMKCoordinateRegion region;
        region.center.latitude     = (maxLat + minLat) / 2;
        region.center.longitude    = (maxLon + minLon) / 2;
        region.span.latitudeDelta  = maxLat - minLat;
        region.span.longitudeDelta = maxLon - minLon;
        [navView setRegion:region];
    }
}


#pragma mark -
- (IBAction)ChangeMapScale:(id)sender {
    if (stepper.value < stepper.tag) {
        //缩小
        [navView zoomOut];
        stepper.value--;
    }
    else {
        //放大
        [navView zoomIn];
        stepper.value++;
    }
    
    stepper.tag = stepper.value;
}

#pragma mark - BMKMapViewDelegate
/**
 *返回驾乘搜索结果
 *@param result 搜索结果
 *@param error 错误号，@see BMKErrorCode
 */
- (void)onGetDrivingRouteResult:(BMKPlanResult*)result errorCode:(int)error{
    [UIView animateWithDuration:0.3f animations:^(void){
        [rightActivityView setAlpha:0.0f];
        [rightActivityLoadingView stopAnimating];
    }];
    //	NSLog(@"onGetDrivingRouteResult:error:%d", error);
	if (error == BMKErrorOk) {
		BMKRoutePlan* plan = (BMKRoutePlan*)[result.plans objectAtIndex:0];
		
		RouteAnnotation2* item = [[RouteAnnotation2 alloc] init];
		item.coordinate = result.startNode.pt;
		item.title = @"我的位置";
		item.type = 0;
		[navView addAnnotation:item];
		
		int index = 0;
		int size = [plan.routes count];
		for (int i = 0; i < 1; i++) {
			BMKRoute* route = [plan.routes objectAtIndex:i];
			for (int j = 0; j < route.pointsCount; j++) {
				int len = [route getPointsNum:j];
				index += len;
			}
		}
		
		BMKMapPoint* points = NULL;// = BMKMapPoint[index];
        
		index = 0;
		
		for (int i = 0; i < 1; i++) {
			BMKRoute* route = [plan.routes objectAtIndex:i];
			for (int j = 0; j < route.pointsCount; j++) {
				int len = [route getPointsNum:j];
				BMKMapPoint* pointArray = (BMKMapPoint*)[route getPoints:j];
				memcpy(points + index, pointArray, len * sizeof(BMKMapPoint));
				index += len;
			}
			size = route.steps.count;
			for (int j = 0; j < size; j++) {
				BMKStep* step = [route.steps objectAtIndex:j];
				item = [[RouteAnnotation2 alloc]init];
				item.coordinate = step.pt;
				item.title = step.content;
				item.degree = step.degree * 30;
				item.type = 4;
				[navView addAnnotation:item];
                
			}
			
		}
		
		item = [[RouteAnnotation2 alloc] init];
		item.coordinate = result.endNode.pt;
		item.type = 1;
		item.title = [stadiumInfo objectForKey:@"name"];
        item.subtitle = [stadiumInfo objectForKey:@"address"];
		[navView addAnnotation:item];
        
		BMKPolyline* polyLine = [BMKPolyline polylineWithPoints:points count:index];
		[navView addOverlay:polyLine];
//		delete []points;
        
        endAnnotation = item;
        
//        [self selectRegion];
	}else{
        [self performSelector:@selector(hideLoading:) withObject:@"导航失败" afterDelay:0.5f];
        
    }
}


@end
